package com.st.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.util.StringUtils;
import com.st.common.dubboProvider.coupon.CouponDubboService;
import com.st.common.dubboProvider.coupon.CouponReductionService;
import com.st.common.dubboProvider.elasticsearch.UpTo;
import com.st.common.dubboProvider.ware.JudgeWareSkuService;
import com.st.common.to.SkuReductionTo;
import com.st.common.to.SpuBoundTo;
import com.st.common.to.es.SkuEsModel;
import com.st.common.utils.R;
import com.st.mall.product.entity.*;
import com.st.mall.product.service.*;
import com.st.mall.product.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.st.common.utils.PageUtils;
import com.st.common.utils.Query;

import com.st.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService imagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private BrandService brandService;
    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @DubboReference(check = false)
    private CouponDubboService dubboService;

    @DubboReference(check = false)
    private CouponReductionService couponReductionService;
    @DubboReference(check = false)
    private JudgeWareSkuService judgeWareSkuService;
    @DubboReference(check = false)
    private UpTo to;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /*
          status: 2
          key:
          brandId: 9
          catelogId: 225
         */
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if (!StringUtils.isNullOrEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isNullOrEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isNullOrEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catelog_id", catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Transactional
    @Override
    public void saveSpu(SpuSaveVo spuInfo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));

        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuInfo.getImages();
        imagesService.saveImages(spuInfoEntity.getId(), images);


        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(getAttr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(getAttr.getAttrId());
            AttrEntity id = attrService.getById(getAttr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(getAttr.getAttrValues());
            valueEntity.setQuickShow(getAttr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;

        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        // Dubbo远程调用 5、保存spu的积分信息；guli_sms->sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        Bounds bounds = spuInfo.getBounds();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        dubboService.saveCouponBounds(spuBoundTo);

        //5、保存当前spu对应的所有sku信息；
        List<Skus> skus = spuInfo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {

                //5.1）、sku的基本信息；pms_sku_info
                //复制过去的属性值
                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    //1表示是默认图
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                //5.2）、sku的图片信息；pms_sku_image
                List<SkuImagesEntity> entities = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    return skuImagesEntity;

                }).filter(isNeed -> {
                    //返回true就是需要，false就是剔除,fasle没有图片路径的无需保存
                    return !StringUtils.isNullOrEmpty(isNeed.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(entities);

                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //  远程调用 5.4）、sku的优惠、满减等信息；guli   _sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                couponReductionService.saveReduction(skuReductionTo);

            });
        }
    }

    @Transactional
    @Override
    public void spuUp(Long spuId) {
        //查出spuInfo
        SpuInfoEntity spuInfo = this.getById(spuId);
        //查出品牌信息
        BrandEntity brand = brandService.getById(spuInfo.getBrandId());
        //查出spu所有可以被检索规格属性值
        List<ProductAttrValueEntity> forSpu = attrValueService.getAttrBySpuId(spuId);
        List<Long> ids = forSpu.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchIds=attrService.getCouldSearchBy(ids);
        Set<Long> idsSet=new HashSet<>(searchIds);

        List<SkuEsModel.Attrs> attrsList = forSpu.stream().filter(id -> {
            return idsSet.contains(id.getAttrId());
        }).map(setEsAttrs->{
            //将属性值放入es的attrs里面
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(setEsAttrs, attrs);
            return attrs;
        }).collect(Collectors.toList());
  
        //查分类名
        CategoryEntity category = categoryService.getById(spuInfo.getCatalogId());

        //查出spu下所有的sku
        List<SkuInfoEntity> skuLists = skuInfoService.list(new LambdaQueryWrapper<SkuInfoEntity>()
                .eq(SkuInfoEntity::getSpuId, spuId));

        List<SkuEsModel> skuEsModels = skuLists.stream().map(getSku -> {
//            SkuImagesEntity image = skuImagesService.getById(getSku.getSpuId());
            SkuEsModel skuEsModel = new SkuEsModel();
            //拼上sku的信息
            skuEsModel.setSkuImg(getSku.getSkuDefaultImg());
            skuEsModel.setSkuPrice(getSku.getPrice());
            BeanUtils.copyProperties(getSku, skuEsModel);


            //远程查库存
            Map<String, Boolean> haveWare = judgeWareSkuService.isHaveWare(getSku.getSkuId());
            //拼上是否有
            skuEsModel.setHasStock(haveWare.get(String.valueOf(getSku.getSkuId())));

            skuEsModel.setHotScore(0L);
            //拼上品牌信息
            skuEsModel.setBrandImg(brand.getLogo());
            skuEsModel.setBrandName(brand.getName());
            //拼上分类名
            skuEsModel.setCatalogName(category.getName());
            //拼上attr属性信息
            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 远程上架
        R r = to.upTo(skuEsModels);

        //TODO 修改上架状态
        //code=10000表示上架成功
        if((int)r.get("code")==10000){
            spuInfo.setPublishStatus(1);
            spuInfo.setUpdateTime(new Date());
            this.updateById(spuInfo);
        }
    }

}